<template>
  <SplitLayout>
    <div slot="top" class="header-top">
      <SearchForm @query="onQuery" @reset="onResetForm" style="margin:20px 0 0 20px;">
        <SearchFormItem label="预警最晚时间：" style="width:380px;">
          <!-- <a-range-picker v-model="rangeTime" @change="onTimeChange" valueFormat="YYYY-MM-DD" style="width: 100%" /> -->
          <span class="date-range-picker">
            <a-date-picker
              v-model="pageFilter.warningTimeStart"
              placeholder="开始日期"
              :disabled-date="disabledStartDate"
              valueFormat="YYYY-MM-DD"
              @openChange="handleOpenChange($event, 'start')"
            />
            <span class="line">-</span>
            <a-date-picker
              v-model="pageFilter.warningTimeEnd"
              placeholder="结束日期"
              :disabled-date="disabledEndDate"
              valueFormat="YYYY-MM-DD"
              :open="endOpen"
              @openChange="handleOpenChange($event, 'end')"
            />
          </span>
        </SearchFormItem>
        <SearchFormItem label="涉诈网站：" style="width:280px;">
          <a-input v-model="pageFilter.siteUrl" placeholder="请输入" />
        </SearchFormItem>
        <SearchFormItem label="数据来源：" style="width:280px;">
          <!-- <a-input v-model="pageFilter.sourceFlagString" placeholder="请输入数据来源" /> -->
          <j-dict-select-tag
            v-model="pageFilter.sourceFlag"
            placeholder="请选择"
            dictCode="dataSource"
            style="width: 100%"
          />
        </SearchFormItem>
      </SearchForm>
    </div>
    <div class="con-content">
      <div class="con-content-top" :gutter="16" style="display:flex;">
        <downLoadComponents
          ref="downLoadComponents"
          :formData="exportDowmData"
          :apiUrl="downUrl"
          :fileText="fileText + '.xls'"
        >
          <a-button type="primary" @click="onExportDowm">
            导出
          </a-button>
        </downLoadComponents>
      </div>
      <div class="con-content-list">
        <CustomTable
          ref="table"
          :showAlert="false"
          :columns="columns"
          :loading="loading"
          :dataSource="pageData"
          :showSelection="true"
          @selectedRowKey="onSelectedRow"
          @change="onTableChange"
          rowKey="websiteId"
          :scroll="{ x: 1500 }"
        >
          <!-- <template slot="sourceFlagString" slot-scope="text">
            <span v-if="text == 1">国家中心</span>
            <span v-if="text == 2">公安导入</span>
            <span v-if="text == 6">吉林省反炸专业平台</span>
          </template> -->
          <template slot="result" slot-scope="records">
            <a-popconfirm placement="right" ok-text="" cancel-text="">
              <a-icon slot="icon" type="question-circle-o" style="display:none;" />
              <template slot="title">
                <img class="szImg1" :src="JSON.parse(records).data.image" />
              </template>
              <img class="szImg" :src="JSON.parse(records).data.image" />
            </a-popconfirm>
          </template>
          <template slot="sysUserName" slot-scope="text">
            <span v-if="text == null">--</span>
            <span v-else>{{ text }}</span>
          </template>
          <template slot="fzVictimTotalList" slot-scope="text, record, index">
            <a-tag :class="tagFlagArr[index] ? 'tagItem' : ''" v-for="item in record.fzVictimTotalList" :key="item.id">
              <j-ellipsis :value="item.fraudType" :length="5" /> : {{ item.totalNum }}
            </a-tag>
            <a-icon
              v-if="tagFlagArr[index] && record.fzVictimTotalList && record.fzVictimTotalList.length >= 5"
              @click="onTabDownClick(index)"
              class="icon"
              type="caret-down"
              theme="outlined"
              :style="{ fontSize: '26px', color: '#08c' }"
            />
            <a-icon
              v-if="!tagFlagArr[index] && record.fzVictimTotalList && record.fzVictimTotalList.length >= 5"
              @click="onTabDownClick(index)"
              class="icon"
              type="caret-up"
              theme="outlined"
              :style="{ fontSize: '26px', color: '#08c' }"
            />
          </template>
          <!--涉诈域名二维码-->
          <template slot="domainQrcode" slot-scope="text, record">
            <a-dropdown :trigger="['click']" v-model="record.visible" @visibleChange="visibleChange(record)">
              <a> <a-icon type="qrcode" style="color: #4d6583; font-size: 28px" /> </a>
              <div class="custom-ewm" slot="overlay">
                <div :ref="'qrcode' + record.websiteId"></div>
                <a-button type="primary" block style="margin-top: 10px" @click="savePic(record)" v-if="record.visible">
                  下载二维码
                </a-button>
              </div>
            </a-dropdown>
          </template>
        </CustomTable>
      </div>
    </div>
  </SplitLayout>
</template>
<script>
import SearchForm from '@/components/zxd/SearchForm'
const SearchFormItem = SearchForm.Item
import { SplitLayout } from '@/components/zxd/layouts'
import CustomTable from '@/components/zxd/Table/CustomTable'
import downLoadComponents from '@/components/zxd/downLoad'
import { listWebsitePortrait, serviceName } from '@/api/modules/feedbackManagement.js'
import QRCode from 'qrcodejs2'
import { isURL } from '@/utils/validate'
export default {
  components: {
    SearchForm,
    SearchFormItem,
    CustomTable,
    SplitLayout,
    downLoadComponents
  },
  data() {
    return {
      pageData: [],
      endOpen: false,
      loading: false,
      columns: [
        {
          title: '涉诈网站截图',
          dataIndex: 'result',
          align: 'center',
          width: 120,
          fixed: 'left',
          scopedSlots: { customRender: 'result' }
        },
        {
          title: '涉诈网站',
          dataIndex: 'siteUrl',
          align: 'center',
          fixed: 'left',
          width: 120,
          scopedSlots: { customRender: 'siteUrl' }
        },
        {
          title: '截图时间',
          width: 200,
          dataIndex: 'screenshotTime',
          align: 'center'
        },
        {
          title: '涉诈网站二维码',
          dataIndex: 'domainQrcode',
          width: 130,
          align: 'center',
          scopedSlots: { customRender: 'domainQrcode' }
        },
        {
          title: '诈骗类型累计次数',
          dataIndex: 'fzVictimTotalList',
          align: 'left',
          width: '40vh',
          scopedSlots: { customRender: 'fzVictimTotalList' }
        },
        {
          title: '响应码',
          dataIndex: 'responseCode',
          align: 'center',
          width: 120
        },
        {
          title: '涉诈网站标题',
          dataIndex: 'siteTitle',
          align: 'center',
          width: 120
        },
        {
          title: '预警最早时间',
          dataIndex: 'warningTimeStart',
          align: 'center',
          width: 160
        },
        {
          title: '预警最晚时间',
          dataIndex: 'warningTimeEnd',
          align: 'center',
          width: 160
        },
        {
          title: '数据来源',
          dataIndex: 'sourceFlagString',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'sourceFlagString' }
        }
      ],
      pageFilter: {
        pageNo: 1, // 当前页数
        pageSize: 10 // 每页显示几条数据
      },
      exportDowmData: { idList: [], websitePortraitQueryVO: {} },
      rangeTime: undefined,
      fileText: '网站画像列表',
      downUrl: `${serviceName}/feedback/feedbackManagent/websitePortraitExportXls`,
      tagFlagArr: [],
      isSelected: true,
      totalListArr: [],
      maxTotal: 0
    }
  },
  mounted() {
    this.refreshTable()
  },
  methods: {
    onSelectedRow(keys) {
      this.exportDowmData = {
        idList: keys,
        websitePortraitQueryVO: {
          siteUrl: this.pageFilter.siteUrl,
          sourceFlag: this.pageFilter.sourceFlag,
          warningTimeEnd: this.pageFilter.warningTimeEnd,
          warningTimeStart: this.pageFilter.warningTimeStart
        }
      }

      this.isSelected = keys.length > 0 ? false : true
    },
    onTabDownClick(index) {
      this.$set(this.tagFlagArr, index, !this.tagFlagArr[index])
    },
    onTimeChange(date, dateString) {
      this.pageFilter.warningTimeStart = dateString[0]
      this.pageFilter.warningTimeEnd = dateString[1]
      this.rangeTime = date
    },
    refreshTable() {
      this.loading = true
      listWebsitePortrait(this.pageFilter)
        .then(res => {
          if (res.success) {
            this.pageData = res.result
            if (this.pageData.records.length > 0) {
              this.totalListArr = []
              this.pageData.records.forEach(item => {
                this.tagFlagArr.push(true)
                //每条数据个数放到数组，然后找出个数最多值
                this.totalListArr.push(item.fzVictimTotalList.length)
              })
              this.maxTotal = this.totalListArr.reduce(function(a, b) {
                return b > a ? b : a
              })
              //根据最大个数设置列的长度
              this.setColumns(this.maxTotal)
            }
          } else {
            this.$message.warning(res.message ? res.message : '请求失败！')
          }
        })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
        .finally(() => {
          this.loading = false
        })
    },
    onQuery() {
      this.$refs.table.onClearRowKeys()
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.$refs.table.onClearRowKeys()
      this.rangeTime = undefined
      this.pageFilter = {
        pageNo: 1, // 当前页数
        pageSize: 10 // 每页显示几条数据
      }
      this.refreshTable()
    },
    onExportDowm() {
      this.$refs.downLoadComponents.exportDowmPOST()
      this.$refs.table.onClearRowKeys()
    },
    // 生成二维码
    crateQrcode(websiteId) {
      let refs = this.$refs['qrcode' + websiteId]
      this.qr = new QRCode(refs, {
        width: 155,
        height: 155, // 高度
        text: this.qrcode, // 二维码内容
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
      this.qr.makeCode(this.qrcode)
    },
    // 显示隐藏二维码
    visibleChange(record) {
      if (record.visible) {
        this.qrcode = isURL(record.accessDomainName) ? record.accessDomainName : 'http://' + record.accessDomainName
        // 使用$nextTick确保数据渲染
        this.$nextTick(() => {
          this.crateQrcode(record.websiteId)
        })
      } else {
        this.$nextTick(() => {
          let refs = this.$refs['qrcode' + record.websiteId]
          this.qr.clear() // 清除二维码
          refs.innerHTML = ''
        })
      }
    },
    // 下载二维码
    savePic(record) {
      // let myCanvas = document.getElementById("qrcode").getElementsByTagName("canvas");
      let myCanvas = this.$refs['qrcode' + record.websiteId].getElementsByTagName('canvas')
      let a = document.createElement('a')
      a.href = myCanvas[0].toDataURL('image/png')
      a.download = '二维码'
      a.click()
    },
    onTableChange(obj) {
      // console.log(obj.sortField)
      // console.log(obj.sortOrder)
      // if (obj.sortField == 'warningTotal') {
      //   if (obj.sortOrder == 'ascend') {
      //     this.pageFilter.sort = 'asc'
      //   } else {
      //     this.pageFilter.sort = 'desc'
      //   }
      // }
      this.pageFilter.pageNo = obj.currentPage
      this.pageFilter.pageSize = obj.pageSize
      this.refreshTable()
    },
    setColumns(num) {
      console.log(num)
      setTimeout(() => {
        if (num == 1) {
          this.$set(this.columns, 4, {
            title: '诈骗类型累计次数',
            dataIndex: 'fzVictimTotalList',
            align: 'left',
            width: '20vh',
            scopedSlots: { customRender: 'fzVictimTotalList' }
          })
        }
        if (num == 2) {
          this.$set(this.columns, 4, {
            title: '诈骗类型累计次数',
            dataIndex: 'fzVictimTotalList',
            align: 'left',
            width: '32vh',
            scopedSlots: { customRender: 'fzVictimTotalList' }
          })
        }
        if (num == 3) {
          this.$set(this.columns, 4, {
            title: '诈骗类型累计次数',
            dataIndex: 'fzVictimTotalList',
            align: 'left',
            width: '45vh',
            scopedSlots: { customRender: 'fzVictimTotalList' }
          })
        }
        if (num >= 4) {
          this.$set(this.columns, 4, {
            title: '诈骗类型累计次数',
            dataIndex: 'fzVictimTotalList',
            align: 'left',
            width: '60vh',
            scopedSlots: { customRender: 'fzVictimTotalList' }
          })
        }
      }, 200)
    },
    // 发送时间-自定义开始日期【不可选择的日期】
    disabledStartDate(startValue) {
      const endValue = Object.keys(this.pageFilter).length > 0 && this.pageFilter.warningTimeEnd
        ? this.$JMoment(this.pageFilter.warningTimeEnd) : null
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() > endValue.valueOf()
    },
    // 发送时间-自定义结束日期【不可选择的日期】
    disabledEndDate(endValue) {
      const startValue = Object.keys(this.pageFilter).length > 0 && this.pageFilter.warningTimeStart
      ? this.$JMoment(this.pageFilter.warningTimeStart) : null
      if (!endValue || !startValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    // 发送时间-自定义日期【控制弹层是否展开】
    handleOpenChange(open, status) {
      if (status==='start' && !open) {
        this.endOpen = true
      }
      if (status==='end') {
        this.endOpen = open
      }
    }
  }
}
</script>
<style scoped lang="less">
.con-content-top {
  margin-bottom: 20px;
}
/deep/#advance-btn {
  display: none;
}
.con-content-top button {
  margin-right: 15px;
}

/deep/ .ant-tag {
  width: 6vw;
  text-align: center;
}

/deep/ .ant-tag {
  margin-top: 10px;
}
/deep/ .tagItem:nth-child(n + 5) {
  display: none;
}
.icon {
  position: absolute;
  right: 0;
  top: 24px;
}
/deep/ .ant-table td {
  position: relative;
  .t0 {
    position: absolute;
    top: 16px;
    left: 34.2%;
    color: #1890ff;
  }
}
.szImg {
  width: 120px;
  cursor: pointer;
}
.szImg1 {
  width: 800px;
}
/deep/.ant-popover-message > .anticon {
  display: none !important;
}
/deep/ .ant-popover-message-title {
  margin-left: 0 !important;
}
.custom-ewm {
  padding: 14px;
  background-color: #fff;
  border: 1px #ccc solid;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
}
.date-range-picker {
  // width: 280px;
  display: inline-flex;
  align-items: center;
  .ant-calendar-picker {
    min-width: 47% !important;
  }
  .line {
    padding: 0 4px;
  }
}
</style>
